package com.example.jucdemo.countDownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author by KoVaVo
 * @Date 2021-09-12 16:35
 * @Desc:
 * countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行
 * 他是通过计数器来实现的，他的初始值是线程的数量，当他的值为0的时候，表示所有的线程执行完毕。
 */
public class countDownLatchDemo {

    public static void main(String[] args) {
      final   CountDownLatch countDownLatch = new CountDownLatch(2);
        System.out.println("主线程");
        ExecutorService ex1 = Executors.newSingleThreadExecutor();
        ex1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("子线程："+Thread.currentThread().getName()+"执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            }
        });
        ex1.shutdown();
        ExecutorService ex2 = Executors.newSingleThreadExecutor();
        ex2.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    System.out.println("子线程："+Thread.currentThread().getName()+"执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            }
        });
        ex2.shutdown();
        System.out.println("等待两个线程执行完毕");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行完事。。。。");
    }
}
